package l2ft.gameserver.taskmanager.tasks;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import l2ft.commons.threading.RunnableImpl;
import l2ft.gameserver.ThreadPoolManager;
import l2ft.gameserver.database.MySql;
import l2ft.gameserver.instancemanager.ReflectionManager;
import l2ft.gameserver.model.Player;

public class TaskVariable
{
	private ScheduledFuture<?> _task;
	private Player _player;
	private TaskType _type;
	
	public static enum TaskType
	{
		Chat_ban,
		Trade_ban,
		Jail;
	}
	
	public TaskVariable(Player player, TaskType type, long time)
	{
		_player = player;
		_type = type;
		_task = ThreadPoolManager.getInstance().schedule(new TaskEnd(), time);
	}
	
	public void shutdown()
	{
		long delay = _task.getDelay(TimeUnit.MILLISECONDS);
		_task.cancel(false);
		MySql.set("REPLACE INTO character_variables (obj_id, type, name, value, expire_time) VALUES (?,'user-var',?,?,?)", _player.getObjectId(), _type.toString(), "true", delay);
	}
	
	/**
	 * Remaining time of the task
	 * @unit TimeUnit.something
	 */
	public long getRemainingTime(TimeUnit unit)
	{
		return _task.getDelay(unit);
	}
	
	public void unset()
	{
		_task.cancel(false);
		removeEffect();
	}
	
	private void removeEffect()
	{
		_player.removeTaskFromList(_type);
		_player.unsetVar(_type.toString());
		switch(_type)
		{
		case Chat_ban:
			_player.sendMessage("You can speak again!");
			_player.sendEtcStatusUpdate();
			break;
		case Trade_ban:
			_player.sendMessage("You can use private shop again!");
			break;
		case Jail:
			_player.unblock();
			_player.standUp();
			_player.teleToLocation(17817, 170079, -3530, ReflectionManager.DEFAULT);
			break;
		}
	}
	
	private class TaskEnd extends RunnableImpl
	{
		@Override
		public void runImpl() 
		{
			removeEffect();
		}
	}
}